package com.lyn.seckill.service.impl;

import com.lyn.seckill.common.error.EnumBusinessError;
import com.lyn.seckill.dao.PromoDoMapper;
import com.lyn.seckill.dataobject.PromoDo;
import com.lyn.seckill.service.PromoService;
import com.lyn.seckill.service.model.PromoModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;

@Service
public class PromoServiceImpl implements PromoService {

    private final PromoDoMapper promoDoMapper;
    @Autowired
    public PromoServiceImpl(PromoDoMapper promoDoMapper) {
        this.promoDoMapper = promoDoMapper;
    }

    @Override
    public PromoModel getPromoByItemId(Integer itemId) {
        // 获取对应商品的秒杀活动信息
        PromoDo promoDo = promoDoMapper.selectByItemId(itemId);
        // DO->MO
        PromoModel promoModel = convertFromDataObject(promoDo);
        if (promoModel == null) {
            return null;
        }
        // 判断当前时间活动的状态
        LocalDateTime now = LocalDateTime.now();
        if (promoModel.getStartTime().isAfter(now)) {
            promoModel.setStatus(EnumBusinessError.PROMO_NOT_START);
        } else if (promoModel.getEndTime().isBefore(now)) {
            promoModel.setStatus(EnumBusinessError.PROMO_FINISHED);
        } else {
            promoModel.setStatus(EnumBusinessError.PROMO_ON_GOING);
        }
        return promoModel;
    }

    private PromoModel convertFromDataObject(PromoDo promoDo) {
        if (promoDo == null) {
            return null;
        }
        PromoModel promoModel = new PromoModel();
        BeanUtils.copyProperties(promoDo,promoModel);
        promoModel.setPromoItemPrice(new BigDecimal(promoDo.getPromoItemPrice()));
        promoModel.setStartTime(promoDo.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        promoModel.setEndTime(promoDo.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        return promoModel;
    }
}
